package com.vsked.test;

import java.io.IOException;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;
import com.hyfd.common.utils.DateTimeUtils;

public class reSubmit {

	public static List<String> connect(){
		List<String> list = new ArrayList<String>();
		try {
			String p = "Lks123456";
//			System.out.println(p);
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://rm-bp15x3195m158018mo.mysql.rds.aliyuncs.com:3306/bosspay?user=lks&password="+p+"&useUnicode=true&characterEncoding=utf8&autoReconnect=true";
			Connection conn = DriverManager.getConnection(url);
			Statement statement = conn.createStatement();
//			ResultSet rs = statement.executeQuery("SELECT a.* from (SELECT * from mp_submit_order where submit_date > '2017-08-17 00:00:00') a LEFT JOIN (SELECT * from mp_order where apply_date > '2017-08-17 00:00:00') b on a.order_id = b.agent_order_id where a.result_code = '0:提交成功' and a.agent_name = 'yijie' and (b.phone is NULL or b.status is null)");
			ResultSet rs = statement.executeQuery("SELECT * from mp_submit_order_ls where agent_name = 'guomei'");
			while(rs.next()){
				list.add(rs.getString("submit_param"));
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	
	
	public static void main(String[] args){
		List<String> list = connect();
		for(String s : list){
			deal(strToMap(s));
		}
	}
	
	public static Map<String,String> strToMap(String str){
		Map<String,String> map = new HashMap<String,String>();
		String[] strArr = str.split("\\|");
		for(String s : strArr){
			String[] sArr = s.split("=");
			map.put(sArr[0], sArr[1]);
		}
		return map;
	}
	
	public static Map<String,Object> deal(Map<String, String> order) {
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			String submitUrl = "http://120.55.185.73:8080/bosspay/order/quotaOrder";//提交地址
			//私钥
			String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKiUtncmErHlibSHU5C4rn16BMpmszx1zmv3Zu0lRJAlzxaJ8ilTamAHsLFCPuw+90LkoDDy6o699xRvDXlw2Sk+kvUPAneAbUtFHwxBtqWP21/jm+n7nreGcxRNHX9dYO2ZoHCkprS+EKkDOOyZbL11NUDZ1CIYy0ftfVVBIwIXAgMBAAECgYAo/K84XNtiwUovyE86+owCGe6cP0gIxSPBAE/YDJ2U5nxpIHTuM0fDvVrqXg7qZYy8iNWh0Q3SUsGGCFIgWp2RkI5aoLfAPFUDI6d5HNYePUjOBdgK57aec/MQvTj3f8Qrypyjkwu+VtbQDD6HZtayzwd1PCSkA9itZYQ2NnWbQQJBAP1oSvvZGiAWatAPxyqFfr8+tHZ8Q9Hz9pcjvij1NYwPaqxAI+39mi1XEJ2B/RmLpaajtQeXyPXZXOzh8T6xTacCQQCqTj+JyfKprYv4V+jE0Qagr4Kr+U2LjOZcLsZwmv1tQ1DiYUK5sSWT0sXhSX9ubf/4DCCqZLRBr0mIgHfK25YRAkAmn6/WJSgTPfd30P/VXlWMRr1w1c3sgVfTf5IrYfyQZYUnzfrr+lx2jq+sojR2oU9VT9x21M6/kirUvDduC84/AkAgoNUzhOlk8Mb8UXtbGeD3MCkM4bqlnd0UlDGYqVkcceUxOgkaooHcjGk0/GvZsGF2GHy5qImQfBDOgi5xQxjBAkEAoL0vxMQFKbOUmrX0P3FAKunVheC+1LDYFqDuYhpa5xmfiGqy9BNHiRT9PakTNOuPRdmr4VBl0r3EkpxcjFmX+A==";
			String callbackUrl = order.get("callbackUrl");//回调地址
			String terminalName = order.get("terminalName");//客户名
			String phoneNo = order.get("phoneNo");//手机号
			String spec = order.get("spec");//获取消费金额,以分为单位
			String orderType = order.get("orderType");//业务类型
			String scope = order.get("scope");//适用范围（默认nation）
			String timeStamp = order.get("timeStamp");
			String customerOrderId = order.get("customerOrderId");//32位订单号
			String Signature = "";// 数据私钥签名
			Signature = sign(callbackUrl, customerOrderId, orderType, phoneNo, scope, spec, terminalName, timeStamp,
					privateKey);
			String param = "terminalName=" + terminalName + "&customerOrderId=" + customerOrderId + "&phoneNo=" + phoneNo
					+ "&orderType=" + orderType + "&scope=" + scope + "&spec=" + spec + "&callbackUrl=" + callbackUrl
					+ "&timeStamp=" + timeStamp + "&signature=" + Signature;
			String result = get(submitUrl+"?"+param);
			JSONObject resultJson = JSONObject.parseObject(result);
			String code = resultJson.getString("code");
			if(code.equals("0")){
				System.out.println(order.get("customerOrderId")+"|成功");
			}else{
				System.out.println(order.get("customerOrderId")+"|失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
	
	
	
	public static String get(String url) {
		System.out.println(url);
		CloseableHttpClient httpClient = null;
		try {
			httpClient = HttpClients.createDefault();
			HttpGet httpget = new HttpGet(url);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();// 设置请求和传输超时时间
			httpget.setConfig(requestConfig);
			CloseableHttpResponse response = httpClient.execute(httpget);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 获取状态行
				//System.out.println(response.getStatusLine());
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String out = EntityUtils.toString(entity, "UTF-8");
					return out;
				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				if(null != httpClient){
					httpClient.close();
				}
			} catch (IOException e) {
			}
		}
		return null;
	} 
	
	/**
	 * 生成签名
	 * 
	 * @param paramMap
	 * @param privateKeyStr
	 * @return
	 * @throws Exception
	 */
	public static String sign(String terminalName, String customerOrderId, String orderType, String privateKeyStr)
			throws Exception {
		byte[] keyByteArray = Base64.decodeBase64(privateKeyStr);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyByteArray);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
		String md5 = md5Param(terminalName, customerOrderId, orderType);

		System.out.println("----测试中，生成的md5:[" + md5 + "]");

		byte[] rsa = encodeBytePrivate(md5.getBytes(), privateKey);

		return Hex.encodeHexString(rsa);
	}
	
	public static String md5Param(String terminalName, String customerOrderId, String orderType) {
		String content = getCustSignature(terminalName, customerOrderId, orderType);
		System.err.println("生成签名的参数:" + content);
		return md5(content);
	}
	public static String getCustSignature(String terminalName, String customerOrderId, String orderType) {
		StringBuilder sb = new StringBuilder();
		sb.append("customerOrderId=" + customerOrderId);
		sb.append("&orderType=" + orderType);
		sb.append("&terminalName=" + terminalName);
		return sb.toString();
	}
	/**
	 * 生成签名
	 * 
	 * @param paramMap
	 * @param privateKeyStr
	 * @return
	 * @throws Exception
	 */
	public static String sign(String callbackUrl, String customerOrderId, String orderType, String phoneNo,
			String scope, String spec, String terminalName, String timeStamp, String privateKeyStr) throws Exception {
		byte[] keyByteArray = Base64.decodeBase64(privateKeyStr);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyByteArray);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
		String md5 = md5Param(callbackUrl, customerOrderId, orderType, phoneNo, scope, spec, terminalName, timeStamp);

		System.out.println("----测试中，生成的md5:[" + md5 + "]");

		byte[] rsa = encodeBytePrivate(md5.getBytes(), privateKey);

		return Hex.encodeHexString(rsa);
	}

	public static String md5Param(String callbackUrl, String customerOrderId, String orderType, String phoneNo,
			String scope, String spec, String terminalName, String timeStamp) {
		String content = getCustSignature(callbackUrl, customerOrderId, orderType, phoneNo, scope, spec, terminalName,
				timeStamp);
		System.err.println("生成签名的参数:" + content);
		return md5(content);
	}

	/**
	 * RSA 加密返回byte[]
	 * 
	 * @param content
	 * @param privateKey
	 * @return
	 * @throws Exception
	 */
	public static byte[] encodeBytePrivate(byte[] content, PrivateKey privateKey) throws Exception {
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, privateKey);
		return cipher.doFinal(content);
	}

	/**
	 * MD5摘要
	 *
	 * @param s
	 * @return
	 */
	public final static String md5(String s) {
		try {
			byte[] btInput = s.getBytes("UTF-8");
			// 获得MD5摘要算法�?MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘�?
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			return Hex.encodeHexString(md);
		} catch (Exception e) {
			return null;
		}
	}

	public static String getCustSignature(String callbackUrl, String customerOrderId, String orderType, String phoneNo,
			String scope, String spec, String terminalName, String timeStamp) {
		StringBuilder sb = new StringBuilder();
		sb.append("callbackUrl=" + callbackUrl);
		sb.append("&customerOrderId=" + customerOrderId);
		sb.append("&orderType=" + orderType);
		sb.append("&phoneNo=" + phoneNo);
		sb.append("&scope=" + scope);
		sb.append("&spec=" + spec);
		sb.append("&terminalName=" + terminalName);
		sb.append("&timeStamp=" + timeStamp);
		return sb.toString();
	}

	/**
	 * 验签
	 * 
	 * @param paramMap
	 * @param signature
	 * @param publicKeyStr
	 * @return
	 * @throws Exception
	 */
	public static boolean verify(String callbackUrl, String customerOrderId, String orderType, String phoneNo,
			String scope, String spec, String terminalName, String timeStamp, String signature, String publicKeyStr)
			throws Exception {
		byte[] keyByteArray = Base64.decodeBase64(publicKeyStr);
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyByteArray);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);

		String md5 = md5Param(callbackUrl, customerOrderId, orderType, phoneNo, scope, spec, terminalName, timeStamp);
		byte[] rsa = decodeBytePublic(Hex.decodeHex(signature.toCharArray()), publicKey);
		return new String(rsa).equals(md5);
	}

	/**
	 * 解密返回byte[]
	 * 
	 * @param content
	 * @param publicKey
	 * @return
	 * @throws Exception
	 */
	public static byte[] decodeBytePublic(byte[] content, PublicKey publicKey) throws Exception {
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, publicKey);
		return cipher.doFinal(content);
	}
	
}
